﻿#region AssemblyInstance.cs
// ============================================================================
// This region will be filled automatically with data if you are working
// for example with Microsoft SourceSafe
//
// Purpose:          
// Specifics: 
// 
// Creation date:    2024/1/3 21:31:07
// Created by:       hao.chen
//
// $Author:        $
// $Date:          $
// $Revision:      $
// $History:       $
// $NoKeywords:    $
// 
// Copyright:      © 2024 YourCompanyName
//                 All Rights Reserved
// ============================================================================
#endregion

using CLVisionHalcon_NC;
using CLVisionTrace;
using HalconDotNet;
using NeuroCheck.PlugInLib.API;
using NeuroCheck.PlugInLib.Base;
using System;
using System.Collections.ObjectModel;
using System.Drawing;
using System.IO;
using System.Reflection;
using System.Threading;
using System.Windows.Forms;

// TODO: Namespace - Modify the namespace to the project namespace
namespace CLVisionHalconNC620
{
    /// <summary>Helper class designated for the implementation of the optional custom menu items
    /// and the possibility to wrap objects must be unique within the entire assembly.
    /// </summary>
    /// <remarks>Instead of Globals.cs this class may not be obfuscated.
    /// </remarks>
    // TODO: Attributes - Include this attribute if you want to implement custom menus
    /*
     [NcPICustomMenu(true)]
    */
    [Obfuscation()]
    public static class AssemblyInstance
    {
        #region --- Event and delegate definitions ----------------------------

        // TODO: CustomMenu - Example event handler
        // /*
        /// <summary>The event handler is called when the menu item is clicked.
        /// </summary>
        /// <param name="e">Event arguments.</param>
        public static void mnuExampleEventHandler(NcPIMenuEventArgs e)
        {
            System.Windows.Forms.MessageBox.Show("A message from the custom menu item event handler.");
            Thread.Sleep(2000);
        }
        //  */

        #endregion ------------------------------------------------------------

        #region --- Private and public fields, except those wrapped by properties
        #endregion ------------------------------------------------------------

        #region --- Constructors, including static constructors ---------------

        /// <summary>Constructor.
        /// </summary>
        static AssemblyInstance()
        {
        }

        #endregion ------------------------------------------------------------

        #region --- Instance public properties (and the private fields they wrap)
        #endregion ------------------------------------------------------------

        #region --- Instance public methods -----------------------------------

        /// <summary>Initializes objects that must be unique within the entire plug-in.
        /// </summary>
        public static void ExitInstance()
        {
        }

        public static HDevProcedure _runProcedure;
        public static HDevProcedureCall _retProcedureCall;

        public static HalconCallerNC nC_Halcon_MultiThread;

        public static Mutex mutex;
        public static HalconCallerNC nC_Halcon;
        /// <summary>Destroy objects that must be unique within the entire plug-in.
        /// </summary>
        public static bool InitInstance()
        {
            try
            {
                string logPath = @"V:\Ncheck\System Output\Plug-in_Logfiles_log";
                if (!Directory.Exists(logPath))
                {
                    Directory.CreateDirectory(logPath);
                }

                //设置NC log路径
                string nC_nameSpace = MethodBase.GetCurrentMethod().DeclaringType.Namespace;
                string nC_log_path = Path.Combine(logPath, nC_nameSpace);
                if (!Directory.Exists(nC_log_path))
                {
                    Directory.CreateDirectory(nC_log_path);
                }


                //实例化Halcon调用实例
                nC_Halcon = new HalconCallerNC(nC_log_path);
                //设置Procedure路径
                nC_Halcon.InitHDevEngineNC(out int a, out string b);
                if (a != 0)
                {
                    MessageBox.Show($"初始化Engine错误：{b}");
                    return false;
                }
                nC_Halcon.AddProcedurePathNC(@"V:\NCheck\Check Routines\HalconProcedures", out int code, out string text);
              nC_Halcon_MultiThread.AddProcedurePathNC(@"V:\NCheck\Check Routines\HalconProcedures", out int code_MultiThread, out string text_MultiThread);



                string prodedurePath_internal = @"V:\Ncheck\Check Routines\HalconProcedures\internal";
                bool res_internal = Directory.Exists(prodedurePath_internal);
                if (!res_internal)
                {
                    MessageBox.Show($"文件夹 {prodedurePath_internal} 不存在");
                    return false;
                }
                else
                {
                    nC_Halcon.AddProcedurePathNC(prodedurePath_internal, out int code1, out string text1);
                    nC_Halcon_MultiThread.AddProcedurePathNC(prodedurePath_internal, out int code1_MultiThread, out string text1_MultiThread);
                    if (code1 == -1)
                    {
                        MessageBox.Show(text1);
                        return false;
                    }
                }

                //添加NC_Procedure路径
                string prodedurePath_NC = @"V:\Ncheck\Check Routines\HalconProcedures\NC_Procedure";
                bool res_NC = Directory.Exists(prodedurePath_NC);
                if (!res_NC)
                {
                    MessageBox.Show($"文件夹 {prodedurePath_NC} 不存在");
                    return false;
                }
                else
                {
                    ExcuteHalconProcParameterDialog.showProcedurePath.Add(prodedurePath_NC);
                    ExcuteHalconProc_MultiThreadParameterDialog.showProcedurePath.Add(prodedurePath_NC);
                    nC_Halcon.AddProcedurePathNC(prodedurePath_NC, out int code2, out string text2);
                    if (code2 == -1)
                    {
                        MessageBox.Show(text2);
                        return false;
                    }
                    nC_Halcon_MultiThread.AddProcedurePathNC(prodedurePath_NC, out int code2_MultiThread, out string text2_MultiThread);
                    if (code2_MultiThread == -1)
                    {
                        MessageBox.Show(text2_MultiThread);
                        return false;
                    }
                }

                /*搜索"V:\Ncheck\Check Routines\HalconProcedures"下所有文件夹中的Procedure
                //string path = @"V:\Ncheck\Check Routines\HalconProcedures";
                //string[] directories = Directory.GetDirectories(path);
                //for (int i = 0; i < directories.Length; i++)
                //{
                //    ExcuteHalconProc.nC_Halcon.AddProcedurePathNC(directories[i], out int code3, out string text3);
                //    string dirctoryName = Path.GetFileName(directories[i]);
                //    if (dirctoryName != "internal")
                //    {
                //        ExcuteHalconProcParameterDialog.showProcedurePath.Add(directories[i]);
                //    }

                //}
                */


                //=====共享内存=======
                //进程间同步
                //mutex = new Mutex(false, "plugin", out bool mutexCreated);


                return true;
            }
            catch (Exception ex)
            {
                Trace.Error("初始化Plug_in时发生错误：" + ex.Message);
                throw new NcPIUserException("初始化Plug_in时发生错误：" + ex.Message);
            }
        }



        #endregion ------------------------------------------------------------

        #region --- Static public methods and properties ----------------------

        // TODO: CustomMenu - Include this method if you want to implement custom menus
        /*
            /// <summary>Creates a collection of custom menu items.
            /// </summary>
            /// <returns>Returns the collection of custom menu items the plug-in provides.</returns>
            public static Collection<NcPIMenuItem> GetCustomMenus()
            {
                // Create a new collection of menu items
                Collection<NcPIMenuItem> colMenuItems = new Collection<NcPIMenuItem>();

                // TODO: CustomMenu - Example code how to create custom menus
                #region --- Example ---

                // Create a new menu item
                NcPIMenuItem mnuExample = new NcPIMenuItem();
                // Assign the event handler is called when the menu item is clicked
                mnuExample.EventHandler = mnuExampleEventHandler;
                // Define an unique ID for the menu item
                mnuExample.ID = 2342;
                // Specify the mode of NeuroCheck the menu is shown
                mnuExample.Mode = NcPIMenuModes.Manual;
                // Optionally assign an icon (16x16 pixel) for the menu item

                //  mnuExample.MenuIcon = new Bitmap(SystemIcons.Information, new Size(16, 16));

                mnuExample.MenuIcon = new Bitmap(Properties.Resources.公司Logo);
                // Define the text of the menu item.
                mnuExample.Text = "Example of a menu item";
                // Add the completely initialized menu item to the menu item collection
                colMenuItems.Add(mnuExample);

                #endregion --- Example ---

                // Return the menu item collection
                return colMenuItems;
            }
        */

        #endregion ------------------------------------------------------------

        #region --- Methods in interfaces -------------------------------------
        #endregion ------------------------------------------------------------

        #region --- Private (helper) methods ----------------------------------
        #endregion ------------------------------------------------------------

    } // end of class
} // end of namespace